package com.example.sunyueproject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.Toast;

public class CameraControl {
	 private static Camera camera;
	 private static MediaRecorder recorder = new MediaRecorder();
	 
	 public static boolean init() {
		 try {
			 camera = Camera.open(); // attempt to get a Camera instance
			 return true;
		 } catch (Exception e) {
			 return false;
		 }
	 }
	 
	 public static void setCallback(PreviewCallback callback) {
		 camera.setPreviewCallback(callback);
	 }
	 
	 public static void adjust() {
		 camera.setDisplayOrientation(90);
	 }
	 
	 public static void startPreview(SurfaceHolder holder) {
		 try {
			 camera.setPreviewDisplay(holder);
	         camera.startPreview();
	     } catch (IOException e) {
	         Log.d("TAG", "Error setting camera preview: " + e.getMessage());
	     }
	 }
	 
	 public static void stopPreview() {
		 try {
			 camera.stopPreview();
		 } catch(Exception e) {
			 Log.d("TAG", "Error stopping camera preview: " + e.getMessage());
		 }
	 }
	 
	 public static void release() {
		 if (camera != null) {
			 camera.setPreviewCallback(null);
			 camera.setPreviewCallbackWithBuffer(null);
			 camera.stopPreview();
			 camera.release();        // release the camera for other applications
			 camera = null;
		 }
	 }
	 
	 
	 public static Camera getCamera() {
		 return camera;
	 }
	 
	 public static void startRecorder(SurfaceHolder holder) { 
		 File tmpfile;
		try {
		 camera.unlock();
		 RTVideoUpload tmp = new RTVideoUpload();
		 tmp.createConnection("", 0);
		 //tmpfile = new File(Environment.getExternalStorageDirectory().getCanonicalFile()+"/tmp.mp4");
		 //FileOutputStream o = new FileOutputStream(tmpfile);
		 recorder.setCamera(camera);
		 recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		 recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); 
		 recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		 recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
		 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
	
		 //recorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_480P));
		 recorder.setOutputFile(tmp.getFd());
		 recorder.setPreviewDisplay(holder.getSurface());
		 
		 recorder.setOrientationHint(90);
		 recorder.prepare();
		 recorder.start();
		} catch (IOException e) {
			Log.d("TAG", "MediaRecorder error: " + e.getMessage());
		}
	 }
	 
	 public static void stopRecorder() {
		 recorder.stop();
		 recorder.reset();
		 recorder.release();
	 }
}

